package com.proxy.demo1;
import java.lang.reflect.InvocationHandler;   
import java.lang.reflect.Method;   
import java.lang.reflect.Proxy;   
import sun.misc.ProxyGenerator;   
import java.io.*;  
/**
 * JDK的动态代理
 * @author wdd-think
 *
 */
public class DynamicProxy {

	public static void main( String args[] )   
	  {   
		// 实例化目标对象  
		Subject real = new RealSubject();   
		System.out.println(Thread.currentThread().getContextClassLoader());
//	    Subject proxySubject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(),new Class[]{Subject.class},new ProxyHandler(real));
	    Subject proxySubject = (Subject)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{Subject.class},new ProxyHandler(real));
	    // 实例化InvocationHandler  
	    ProxyHandler proxyHandler = new ProxyHandler(real);
	    // 根据目标对象生成代理对象  
	    //Subject proxySubject = (Subject) proxyHandler.getProxy();
	    // 调用代理对象的方法
	    proxySubject.doSomething();
	   
	    //write proxySubject class binary data to file   
	    //createProxyClassFile();   
	  }   
	     
	  public static void createProxyClassFile()   
	  {   
	    String name = "ProxySubject";   
	    byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Subject.class } );   
	    try  
	    {   
	      FileOutputStream out = new FileOutputStream( name + ".class" );   
	      out.write( data );   
	      out.close();   
	    }   
	    catch( Exception e )   
	    {   
	      e.printStackTrace();   
	    }   
	  }   
	}  